﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Controls;
using System.Collections.Generic;
using VAdvantage.Classes;

namespace VAdvantage.Grids
{
    public class VGrid:Grid,IDisposable
    {

        private String oldFieldGroup = null;
        /** DefaultFocusField		*/
        private IControl defaultFocusField = null;
        private bool leftToRight = true;

        private bool isFirstTime = true;

        /** Map of group name to list of components in group. */

        Dictionary<FrameworkElement, GridField> compToFieldMap = new Dictionary<FrameworkElement, GridField>();

        /** Map of group name to list of components in group. */
        Dictionary<String, List<FrameworkElement>> groupToCompsMap =
            new Dictionary<String, List<FrameworkElement>>();

        /** Map of group name to list of components in group. */

        public List<IControl> ctrlForBindData = new List<IControl>(5);
        public List<IControl> allControls = new List<IControl>(5);

        /* Action links  4/1/12 */
        public List<IControl> allLinkControls = new List<IControl>(5);


        public void Dispose()
        {
            if (compToFieldMap != null)
                compToFieldMap.Clear();
            compToFieldMap = null;

            if (groupToCompsMap != null)
                groupToCompsMap.Clear();
            groupToCompsMap = null;

            this.Children.Clear();

            foreach (IControl ctrl in allControls)
            {
                if(ctrl is IControl)
                ((IControl)ctrl).Dispose();
            }
        }

        public VGrid()
        {
            SetColumns();
            SetRows();
            this.Margin = new Thickness(2, 10, 2, 5);
        }

        private void SetRows()
        {
            this.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto});
        }

        private void SetColumns()
        {
            this.ColumnDefinitions.Add(
               new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
            this.ColumnDefinitions.Add( 
                new ColumnDefinition() { Width =  GridLength.Auto });
            this.ColumnDefinitions.Add(
              new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
            this.ColumnDefinitions.Add(
               new ColumnDefinition() { Width = new GridLength(15, GridUnitType.Star) });

            this.ColumnDefinitions.Add(
              new ColumnDefinition() { Width = new GridLength(2, GridUnitType.Star) });
            
            this.ColumnDefinitions.Add(
               new ColumnDefinition() { Width = GridLength.Auto });
            this.ColumnDefinitions.Add(
              new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
            this.ColumnDefinitions.Add(
               new ColumnDefinition() { Width = new GridLength(15, GridUnitType.Star) });
            this.ColumnDefinitions.Add(
               new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
        }

      

        int columnIndex = 0;
        //Control lastInsertControl = null;

        /// <summary>
        /// Add Field and Label to Panel
        /// </summary>
        /// <param name="editor"></param>
        /// <param name="mField"></param>
        public void AddField(IControl editor, GridField mField)
        {
            /* Dont Add in control panel */
            if (mField.GetIsLink())
            {
                ctrlForBindData.Add(editor);
                allControls.Add(editor);
                allLinkControls.Add(editor);
                return;
            }

            VLabel label = VControlFactory.GetLabel(mField);
            if (label == null && editor == null)
                return;
            ctrlForBindData.Add(editor);

            bool sameLine = mField.IsSameLine();
            if (AddGroup(mField.GetFieldGroup()))               		//	sets top
                sameLine = false;
            //if (!isFirstTime)
            //{
            if (sameLine)
            {//	Set line #
                if (columnIndex >= 7)
                {
                    sameLine = false;
                    this.RowDefinitions.Add(new RowDefinition(){Height = GridLength.Auto});
                }
                // vTableLayout.Controls.
                //vTableLayout.RowCount -= 1;
                //this.vTableLayout.ResumeLayout(false);
                //this.vTableLayout.PerformLayout();
            }
            else
            {
                columnIndex = 0;
                this.RowDefinitions.Add(new RowDefinition(){Height = GridLength.Auto});
            }
            // }
            //	*** The Label ***
            if (label != null)
            {
                //label.Anchor = AnchorStyles.None;

                //label.Anchor = AnchorStyles.Right;
                //label.AutoSize = true;
                label.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;

                if(mField.GetDescription().Length>0)
                {
                    ToolTipService.SetToolTip(label, mField.GetDescription());
                }

                //	Set column #
                if (leftToRight)
                {
                    //vTableLayout.Controls.Add(label, sameLine ? 5 : 1, vTableLayout.RowCount - 1);
                    this.Children.Add(label);
                    Grid.SetColumn(label,sameLine ? 5 : 1);
                    Grid.SetRow(label,this.RowDefinitions.Count-1);

                }
                //m_gbc.gridx = sameLine ? 2 : 0;
                else
                {
                    //   m_gbc.gridx = sameLine | mField.isLongField() ? 3 : 1;
                }
                AddToCompList(label);
                compToFieldMap.Add(label, mField);
                allControls.Add(label);
                columnIndex = sameLine ? 6 : 0;


                //Control ctrl = GetLabel();


                if (leftToRight)
                {
                    //vTableLayout.Controls.Add(ctrl, sameLine ? 6 : 2, vTableLayout.RowCount - 1);
                }
                //m_gbc.gridx = sameLine ? 2 : 0;
                else
                {
                    //    //   m_gbc.gridx = sameLine | mField.isLongField() ? 3 : 1;
                }

            }

            if (editor != null)
            {
                FrameworkElement field = null;
                if (editor is VTextBlock)
                {
                    field = ((VTextBlock)editor).GetLabel();
                }
                else
                {
                     field= (FrameworkElement)editor;
                }
                
                //field.Anchor = AnchorStyles.None;
                if (field is VCheckBox)
                {
                    field.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                }

                else if (field is VComboBox) //Zoom Button
                {
                    VComboBox cmb = field as VComboBox;
                    if (cmb.GetzoomButton() != null)
                    {
                        Control zoom = cmb.GetzoomButton();
                        Grid grd = new Grid();
                        //grd.Background = new SolidColorBrush(Colors.Blue);
                        grd.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                        grd.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
                        grd.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

                        grd.Children.Add(field);
                        grd.Children.Add(zoom);
                        Grid.SetColumn(zoom,1);
                        field = grd;
                    }
                }
                else if(field is VTextBoxButton)
                {
                    VTextBoxButton cmb = field as VTextBoxButton;
                    if (cmb.GetzoomButton() != null)
                    {
                        Control zoom = cmb.GetzoomButton();
                        Grid grd = new Grid();
                        //grd.Background = new SolidColorBrush(Colors.Red);
                        grd.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                        grd.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
                        grd.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

                        grd.Children.Add(field);
                        grd.Children.Add(zoom);
                        Grid.SetColumn(zoom,1);
                        field = grd;
                    }
                }

                else
                {
                   field.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;// . Anchor = AnchorStyles.Left;   
                }
                field.Margin = new Thickness(1,4,1,3);
                if (leftToRight)
                {
                    //vTableLayout.Controls.Add(field, sameLine ? 7 : 3, vTableLayout.RowCount - 1);
                    try
                    {
                        this.Children.Add(field);
                        Grid.SetColumn(field, sameLine ? 7 : 3);
                        Grid.SetRow(field, this.RowDefinitions.Count - 1);
                    }
                    catch
                    {

                    }
                }
                else
                {
                    //   m_gbc.gridx = sameLine ? 2 : 0;
                }
                //vTableLayout.SetColumnSpan(field, (!sameLine && mField.IsLongField()) ? 5 : 1);
                Grid.SetColumnSpan(field, (!sameLine && mField.IsLongField()) ? 5 : 1);
                if (!sameLine && mField.IsLongField())
                {
                    field.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;// Dock = DockStyle.Fill;
                }

                AddToCompList((FrameworkElement)field);
                compToFieldMap.Add((FrameworkElement)field, mField);
                allControls.Add(editor);
                columnIndex = sameLine || mField.IsLongField() ? 7 : 5;

                //	Default Focus
                if (defaultFocusField == null && mField.IsDefaultFocus())
                {
                    defaultFocusField = editor;
                    //field.Focus();
                    //if (s_focusPolicy == null)
                    //    s_focusPolicy = new AFocusTraversalPolicy();
                    //setFocusTraversalPolicy(s_focusPolicy);
                    //setFocusTraversalPolicyProvider(true);
                }
            }



        }


        private Control GetLabel()
        {
            //Panel p = new Panel();
            //p.Size = new System.Drawing.Size(0, 10);
            //p.Dock = DockStyle.Fill;
            ////p.BorderStyle = BorderStyle.FixedSingle;
            //Label lbl = new Label();
            //lbl.Text = "..............................................................";
            //lbl.AutoSize = true;
            //lbl.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
            //lbl.Anchor = AnchorStyles.Left;
            ////lbl.AutoEllipsis = true;
            ////lbl.Padding = new Padding(0, 0, 0, 0);

            //p.Controls.Add(lbl);
            ////lbl.Size = new System.Drawing.Size(0, 30);
            ////lbl.Dock = DockStyle.Fill;
            return null;// p;
        }

        /// <summary>
        /// Add Field Group 
        /// </summary>
        /// <param name="fieldGroup"></param>
        /// <returns></returns>
        private bool AddGroup(string fieldGroup)
        {
            ////return false;
            ////	First time - add top
            if (oldFieldGroup == null)
            {
                //addTop();
                oldFieldGroup = "";
            }
            if (fieldGroup == null || fieldGroup.Length == 0 || fieldGroup.Equals(oldFieldGroup))
                return false;
            oldFieldGroup = fieldGroup;

            VLine fp = new VLine(fieldGroup);
            fp.OnClick += new RoutedEventHandler(fp_OnClick);

            this.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            //vTableLayout.RowCount++;
            //vTableLayout.Controls.Add(fp, 1, vTableLayout.RowCount - 1);
            //vTableLayout.SetColumnSpan(fp, 7);
            this.Children.Add(fp);
            Grid.SetColumn(fp, 1);
            Grid.SetRow(fp, this.RowDefinitions.Count-1);
            Grid.SetColumnSpan(fp,7);
            return true;
        }

        void fp_OnClick(object sender, RoutedEventArgs e)
        {

            VAdvantage.Controls.VLine.VLineEventArgs args = (VAdvantage.Controls.VLine.VLineEventArgs)e;
            //System.Drawing.Size minSize = vTableLayout.MinimumSize;
            //vTableLayout.MinimumSize = new System.Drawing.Size(vTableLayout.MinimumSize.Width, 0);
            //vTableLayout.AutoSize = true;
           // vTableLayout.SuspendLayout();
            List<FrameworkElement> comp = groupToCompsMap[args.Name];

            bool isCollapse = !args.IsExpand;
            foreach (FrameworkElement ctrl in comp)
            {
                GridField field = compToFieldMap[ctrl];
                //field.Isdisplayed(true);
                ctrl.Visibility = !isCollapse && field.IsDisplayed(true) ?Visibility.Visible:Visibility.Collapsed;
                ctrl.Tag = !isCollapse;
            }
            //vTableLayout.ResumeLayout(false);
            //vTableLayout.PerformLayout();

            //vTableLayout.MinimumSize = new System.Drawing.Size(vTableLayout.MinimumSize.Width, vTableLayout.PreferredSize.Height);
            //vTableLayout.AutoSize = false;

            //vTableLayout.Height = vTableLayout.PreferredSize.Height;
           // vTableLayout.Width = this.Width - 22;
        }

        private void AddToCompList(FrameworkElement comp)
        {
            if (oldFieldGroup != null && !oldFieldGroup.Equals(""))
            {
                List<FrameworkElement> compList = null;

                groupToCompsMap.TryGetValue(oldFieldGroup, out compList);
                if (compList == null)
                {
                    compList = new List<FrameworkElement>();
                    groupToCompsMap.Add(oldFieldGroup, compList);
                }
                compList.Add(comp);
            }
        }
            /// <summary>
        ///Request Focus In Window
        /// </summary>
        /// <returns></returns>
        public bool RequestFocusInWindow()
        {
            if (defaultFocusField != null)
            {
                if (!defaultFocusField.GetIsReadonly())
                {
                    //((Control)defaultFocusField). Select();
                    return ((Control)defaultFocusField).Focus();
                    //  .getFocusableComponent().requestFocusInWindow();
                }
            }
            return false;
        }
        
    }
}
